<?php
use \Illuminate\Database\Eloquent\ModelNotFoundException;

class BaseArticleController extends BaseController {
	
	protected $layout = 'layouts.master';

    /**
     * 
     * 
     * @param $viewName
     * @param $articleType
     * @param $orderBy
     * @param $subDays      多少天以内
     */
	protected function getArticleListView($viewName, $articleType, $orderBy = 'created_at', $subDays = null)
	{
        $q 				= Input::get('q', '');
        $page 			= Input::get('page', 1);
        $cat_id 		= Input::get('cat_id', 0);
        $orderBy 		= Input::get('order', 'created_at');
        $rows_per_page 	= Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset 		= ($page-1) * $rows_per_page;

        $rules = array (
            'cat_id' 		=> 'numeric|min:1',
            'page' 			=> 'numeric|min:1',
            'rows_per_page' => 'numeric|min:1',
        );
        $messages = array(
            'cat_id.numeric' 		=> 'cat_id需要是数字',
            'cat_id.min' 			=> 'cat_id不能少于1',
            'page.numeric' 			=> 'page需要是数字',
            'rows_per_page.numeric' => 'rows_per_page需要是数字',
        );
        $validator = Validator::make ( Input::all(), $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        try {
            $articles = Article::getArticles($articleType, $q, $cat_id, $offset, $rows_per_page, $orderBy, null, $subDays, Article::STATUS_APPROVED, null);
        } catch (Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '咨询律师失败，请稍后再试。',
                503
            );
        }
        $articleList = [];
        foreach($articles as $article) {
            $articleItem = $this->preprocessArticleItem($article, $includeComments = false, $listView = true);
            
            $created_at = strtotime($articleItem['created_at']);
            $articleItem["year"] = date('Y',$created_at);
            $articleItem["time"] = date('h:i',$created_at);
            $articleList[] = $articleItem;
//             $articleList[] = $article->toArray();
        }
        return $this->makeView($viewName, $articleList);
	}

    protected function articleView($id, $viewName, $articleType = null)
    {
         $article = Article::find($id);
         if(!$article){
            return $this->makeView(
                'errors.404',
                '没有找到符合要求的纪录。',
                404
            );
         }
         if(!is_null($articleType) && $article->class != $articleType){
            return $this->makeView(
                'errors.404',
                '没有找到符合要求的纪录。',
                404
            );
         }
        try {
            // 增加浏览次数
            $article->increment('hits');
            $article->touch();
            $article->save();
        } catch(Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '请稍后再试。',
                503
            );
        }
        $articleArr = $this->preprocessArticleItem($article);
        return $this->makeView($viewName, $articleArr);
    }
	
    /**
     * Todos: include comments
     */
    protected function preprocessArticleItem($article, $includeComments = false, $listView = false)
    {
        $articleArr = $article->toArray();
        $articleItem = [];
        $articleItem['id'] = $articleArr['id'];
        $articleItem['info'] = $articleArr['info'];
        $articleItem['title'] = $articleArr['title'];
        $articleItem['created_at'] = $articleArr['created_at'];
        $articleItem['comments_count'] = $articleArr['comments'];
        $articleItem['likes_count'] = $articleArr['likes'];
        $articleItem['views_count'] = $articleArr['hits'];
        $articleItem['collects_count'] = $articleArr['collects_count'];
        $articleItem['downs'] = $articleArr['downs'];
        $articleItem['content'] = $article->articleContent();
        $articleItem['class'] = $article->getClass();
        $articleItem['law_cat'] = $article->getLawCat();
        $articleItem['wechat_url'] = Config::get('app.wechat_web_url') . '/#/knowledge/view/' . $articleArr['id'];
        if (Auth::check()) {
            $articleItem['is_collect'] = $article->isCollect();
            $articleItem['is_like'] = $article->isLiked();
        } else {
            $articleItem['is_collect'] = null;
            $articleItem['is_like'] = null;
        }
        $articleItem['author'] = $article->getAuthor();
        $default= "img/default_imgs/[]".rand(1,19).".png";
        $articleItem['img'] = UtilsHelper::getImage($articleArr['img'],$default);
        $attachment = FileAttachment::findAttachmentByItem($articleItem['id'], FileAttachment::ITEM_TYPE_ARTICLE);
        if ($attachment) {
            $articleItem['file_path'] = route('file.download_file_with_id', array('id'=>$attachment->id));
        } else if ($articleArr['file_path']) {
            $articleItem['file_path'] = route('file.download_file') . '?path=' . $articleArr['file_path'];
        }

//         if ($includeComments) {
//             $articleItem['comments'] = $articleArr['comments'];
//         }
        return $articleItem;
    }
}